﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LFramework.Data
{
    /// <summary>
    /// 数据工厂
    /// </summary>
    public static class DBFactory
    {
        /// <summary>
        /// 根据节点生成数据库访问对象
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static IDBHelper Create(DataSourceInfo ds)
        {
            try
            {
                string connString;

                switch (ds.DsType)
                {
                    case DbTypeEnum.SqlServer:
                        connString = ConnectionStringBuilder.BuildSqlServerConnectionString(ds);
                        return new SqlServerHelper(connString);
                    case DbTypeEnum.Oracle:
                        connString = ConnectionStringBuilder.BuildOracleConnectionString(ds);
                        return new OracleHelper(connString);
                    default:
                        throw new Exception("未支持的数据库类型");
                }

                throw new Exception("未支持的数据库类型");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 从配置文件生成数据库访问对象
        /// </summary>
        /// <param name="name">连接字符串名称</param>
        /// <returns></returns>
        public static IDBHelper CreateFromConfig(string name)
        {
            try
            {
                DbTypeEnum dbType;

                string connString = ConnectionStringBuilder.GetConnectionStringFromConfig(name, out dbType);

                switch (dbType)
                {
                    case DbTypeEnum.SqlServer:
                        return new SqlServerHelper(connString);
                    case DbTypeEnum.Oracle:
                        return new OracleHelper(connString);
                    case DbTypeEnum.Access:
                        return new AccessHelper(connString);
                    default:
                        throw new Exception("未支持的数据库类型");
                }

                throw new Exception("未支持的数据库类型");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
